// component/wx-index-list/wx-index-list.js
import { getCourseList } from '../../http/game'
Component({
    /**
     * 组件的属性列表
     */
    properties: {
        /**
         * 城市数据
         */
        data: {
            type: Object,
            value: {},
            observer: function(newVal, oldVal) {
                this.resetRight(newVal);
            }
        },
        /**
         * 配置项
         */
        config: {
            type: Object,
            value: {
                horizontal: true, // 第一个选项是否横排显示（一般第一个数据选项为 热门城市，常用城市之类 ，开启看需求）
                animation: true, // 过渡动画是否开启
                search: true, // 是否开启搜索
                searchHeight: 45, // 搜索条高度
                suctionTop: true // 是否开启标题吸顶
            }
        },
        /**
         * 是否定位我的位置
         */
        myCity: {
            type: Boolean,
            value: false,
        },
        // 用于外部组件搜索使用
        search: {
            type: String,
            value: "",
            observer: function(newVal, oldVal) {
                this.value = newVal;
                this.searchCourse();
            }
        },
        source: {
            type: String,
            value: ''
        }
    },

    data: {
        picker_display: false,
        courseVal: '',
        list: [],
        Array: [],
        rightArr: [], // 右侧字母展示
        jumpNum: '', //跳转到那个字母
        myCityName: '请选择', // 默认我的城市
        topGroup: [], // 内容高度数据
        pos: {
            isTop: false,
            y: 0,
            oldIndex: -1
        },
        listIndex: 0,
        moveDistance: 0,
        province_num: -1,
        city_num: -1,
        isSearch: false
    },
    ready() {
        this.getCourseList()
        // let data = this.data.data;
        // this.resetRight(data);
        // if (this.data.myCity) {
        //   this.getCity()
        // }
    },
    methods: {
        /**
         * 城市展开
         */
        province_click(e) {
            if (e.currentTarget.dataset.num == this.data.province_num) {
                this.setData({
                    province_num: -1
                })
            } else {
                this.setData({
                    province_num: e.currentTarget.dataset.num
                })
            }
        },
        city_click(e) {
            if (e.currentTarget.dataset.num == this.data.city_num) {
                this.setData({
                    city_num: -1
                })
            } else {
                this.setData({
                    city_num: e.currentTarget.dataset.num
                })
            }
        },
        /**
         * 数据重新渲染
         */
        resetRight(data) {
            let rightArr = []
            for (let i in data) {
                if (data[i].length > 0) {
                    rightArr.push(i);
                }
            }
            this.setData({
                list: data,
                rightArr
            }, () => {
                if (data.length != 0) {
                    this.queryMultipleNodes();
                }
            })
        },
        jumpMt(e) {
            let jumpNum = e.currentTarget.dataset.id;
            this.setData({
                jumpNum
            });
        },
        async getCourseList() {
            const location = wx.getStorageSync('location')
            const { data } = await getCourseList(location)
            console.log(data);
            this.setData({
                nearCourse: data.near,
                courseList: data.list
            })
        },
        /**
         * 列表点击事件
         */
        async detailMt(e) {
            const { province, city } = e.currentTarget.dataset.detail
            // 获取球场列表
            const { data } = await getCourseList({ province, city })
            this.setData({
                Array: data,
                picker_display: true
            });
            this.showModal();
        },
        // 选择球场后的执行事件
        pickerChange(data) {
            const course = data.currentTarget.dataset.detail
            this.setData({ course })
            if (this.data.source === 'ball') {
                this.triggerEvent('picker', course)
            } else {
                this.selectComponent("#popup-half").showPopup()
            }
        },
        // 获取搜索输入内容
        input(e) {
            this.value = e.detail.value;
        },
        //显示对话框
        showModal: function() {
            // 显示遮罩层
            var animation = wx.createAnimation({
                duration: 200,
                timingFunction: "linear",
                delay: 0
            })
            this.animation = animation
            animation.translateY(300).step()
            this.setData({
                animationData: animation.export(),
                showModalStatus: true
            })
            setTimeout(function() {
                animation.translateY(0).step()
                this.setData({
                    animationData: animation.export()
                })
            }.bind(this), 200)
        },
        //隐藏对话框
        hideModal: function() {
            // 隐藏遮罩层
            var animation = wx.createAnimation({
                duration: 200,
                timingFunction: "linear",
                delay: 0
            })
            this.animation = animation
            animation.translateY(300).step()
            this.setData({
                animationData: animation.export(),
            })
            setTimeout(function() {
                animation.translateY(0).step()
                this.setData({
                    animationData: animation.export(),
                    showModalStatus: false
                })
            }.bind(this), 200)
        },
        /**
         * 搜索相关逻辑实现
         */
        deepClone(obj) {
            const _obj = JSON.stringify(obj)
            return JSON.parse(_obj)
        },
        bindSearchInput(e) {
            this.setData({
                courseVal: e.detail.value
            })
            if (e.detail.value === '' || e.detail.value === 'undefined') {
                this.setData({
                    isSearch: false
                })
            }
        },
        searchCourse() {
            let list = this.deepClone(this.data.courseList);
            let search = this.data.courseVal

            let result = list.filter(item => item.course_name.indexOf(search) > -1)
            this.setData({
                isSearch: true,
                resultData: result
            })
            // if (this.value == '' || this.value == undefined) {
            //     this.resetRight(data)
            // } else {
            //     for (let i in data) {
            //         for (let j = 0; j < data[i].length; j++) {
            //             for (let q = 0; q < data[i][j].city_list.length; q++) {
            //                 for (let n = 0; n < data[i][j].city_list[q].court_list.length; n++) {
            //                     if (data[i][j].city_list[q].court_list[n].court_name.indexOf(this.value) == -1) {
            //                         data[i][j].city_list[q].court_list.splice(n, 1)
            //                         n = n - 1
            //                     }
            //                 }
            //                 if (data[i][j].city_list[q].court_list.length < 1) {
            //                     data[i][j].city_list.splice(q, 1)
            //                     q = q - 1
            //                 }
            //             }
            //             if (data[i][j].city_list.length < 1) {
            //                 data[i].splice(j, 1)
            //                 j = j - 1
            //             }
            //         }
            //     }
            //     this.resetRight(data);
            // }

        },
        // 城市定位
        locationMt() {
            // TODO 暂时没有实现 定位自己的城市，需要引入第三方api
        },
        /**
         * 监听滚动
         */
        scroll(e) {
            let top = e.detail.scrollTop
            let index = this.currentIndex(top)
            let list = this.data.topGroup
            let distance = top - list[this.data.listIndex]
            let num = -(list[this.data.listIndex + 1] - top - 40)
            // 渲染滚动索引
            if (index !== this.data.listIndex) {
                this.setData({
                    listIndex: index,
                    moveDistance: 40,
                })
                // 如果监听到 index 的变化 ，一定要return ，否则吸顶会先变化文字后运动，会闪烁
                return
            }
            if (num < 0) num = 0
            if (num !== this.data.moveDistance) {
                this.setData({
                    moveDistance: num,
                })
            }
        },
        /**
         * 获取当前滚动索引
         */
        currentIndex(y) {
            let listHeight = this.data.topGroup
            for (let i = 0; i < listHeight.length; i++) {
                let height1 = listHeight[i]
                let height2 = listHeight[i + 1]
                if (!height2 || (y >= height1 && y < height2)) {
                    return i
                }
            }
            return 0
        },
        /**
         * 获取节点信息
         */
        queryMultipleNodes() {
            let self = this
            const query = wx.createSelectorQuery().in(this);
            query.selectAll('.fixed-title-hock').boundingClientRect((res) => {
                res.forEach(function(rect) {
                    rect.top // 节点的上边界坐标
                })
            }).exec((e) => {
                let arr = []
                e[0].forEach((rect) => {
                    let num = 0
                    if (rect.top !== 0) {
                        num = rect.top - (self.data.config.search ? self.data.config.searchHeight : 0)
                    }
                    arr.push(num)
                })
                this.setData({
                    topGroup: arr
                })
            })
        },
        _success(e) {
            this.selectComponent("#popup-half").hidePopup()
            this.triggerEvent('picker', e.detail)
        },
        _error() {
            this.selectComponent("#popup-half").hidePopup()
        },
    }
})